﻿using WebApp.BLL;
using WebApp.BLL.Manage;
using WebApp.Common.EFQuery;
using WebApp.Models;
using StackExchange.Profiling;
using StackExchange.Profiling.Data;
using StackExchange.Profiling.EntityFramework6;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Timers;
using WebApp.Common;
using kzjd.rycp.WebApp.App_Start;
using System.Net;
using System.IO;
using System.Threading;
using WebApp.ViewModels.Manage;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        //IScheduler sched;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ModelBinders.Binders.Add(typeof(QueryModel), new QueryModelBinder());

            ////定义定时器 
            //System.Timers.Timer myTimer = new System.Timers.Timer(60000);
            //myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
            //myTimer.Enabled = true;
            //myTimer.AutoReset = true;
        }

        //protected void myTimer_Elapsed(object source, ElapsedEventArgs e)
        //{
        //    try
        //    {
        //        ((System.Timers.Timer)source).Stop();

        //        //定时检查需要提醒填写使用反馈的申请单，并发送邮件提醒
        //        new T_applyService().SendFeedbackRemindEmailAsync();
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(ex);
        //    }
        //    finally
        //    {
        //        ((System.Timers.Timer)source).Start();
        //    }
        //}

        protected void Application_End(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest()
        {
            if (Request.IsLocal)
            {
                MiniProfiler.Start();
            }
        }

        protected void Application_EndRequest()
        {
            MiniProfiler.Stop();
        }

        /// <summary>
        /// 在出现未处理的错误时运行的代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            log.Error(exception);
            //Response.Clear();
            //HttpException httpException = exception as HttpException;
            //if (httpException != null)
            //{
            //    string action;
            //    switch (httpException.GetHttpCode())
            //    {
            //        case 404:
            //            // page not found
            //            action = "HttpError404";
            //            break;
            //        case 500:
            //            // server error
            //            action = "HttpError500";
            //            break;
            //        default:
            //            action = "Index";
            //            break;
            //    }
            //    //// clear error on server
            //    //Server.ClearError();
            //    Response.Redirect(String.Format("~/Error/{0}/", action));
            //}
        }

        protected void Application_PreSendRequestHeaders()
        {
            Response.Headers.Remove("Server");
            Response.Headers.Remove("X-AspNet-Version");
            Response.Headers.Remove("X-AspNetMvc-Version");
            //Response.Headers.Add("X-XSS-Protection", "1");
            //Response.Headers.Add("X-Frame-Options", "ALLOW-FROM");
            //Response.Buffer = true;
            //Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            //Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            //Response.Expires = 0;
            //Response.CacheControl = "no-cache";
            //Response.Cache.SetNoStore();
        }

        public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            var pars = custom.Split(',');
            if (pars.Length == 0) return string.Empty;

            var res = new System.Text.StringBuilder();
            foreach (var s in pars)
            {
                switch (s)
                {
                    case "user":
                        SessionUserModel user = SessionManage.User;
                        if (user != null)
                        {
                            res.Append(Convert.ToString(user.Id));
                        }
                        else {
                            res.Append("guest");
                        }
                        break;
                    default:
                        var par = context.Request[s];
                        if (par != null)
                            res.AppendFormat(par);
                        break;
                }
            }
            return base.GetVaryByCustomString(context, res.ToString());
        }
    }
}
